

clear
set more off

// author: Lucas


cap log close
log using "$logdir/analysis/line_by_line.log", replace


local incvar soi_agi
do "$adir/get_bad_dummies"

local klist wages int div sched1 pens_ira cg agi txbl_incm eitc ctc


use $statadir/soi_cdw_taxsim_2019 if nonfiler == 0, clear
qui keep if cdw_tu_match

// calculate SOI tax liability

qui drop if nonfiler


get_bad_dummies


gen cdw_sched1 = cdw_nonprop + cdw_nec + cdw_f1065_royal + cdw_f1120s_royal + ///
		cdw_f1065_gp_prim + cdw_f1065_gp_sec + cdw_f1065_ord + cdw_f1120s_ord


gen y_wages = 1-bad_wages
gen denom_wages = soi_wages > 0

gen y_int = 1-bad_int
gen denom_int = soi_interest_txbl > 0

gen y_div = 1-bad_qual_div
gen denom_div = soi_qual_divs > 0

gen y_sched1 = abs(soi_sched_1_incm - cdw_sched1) < 500
gen denom_sched1 = cdw_sched1 ~= 0


gen y_pens_ira = 1 - bad_txbl_pens
gen denom_pens_ira = soi_pens_anns_txbl + soi_ira_dist_txbl > 0

gen y_cg = abs(cdw_stcg + cdw_ltcg - soi_sched_d_capgains_short - soi_sched_d_capgains_long) < 500
gen denom_cg = soi_sched_d_capgains_short + soi_sched_d_capgains_long ~= 0

gen y_agi = abs(soi_agi - taxsim1_agi) < 500
gen denom_agi = soi_agi > 0

gen y_txbl_incm = abs(soi_txbl_incm - taxsim1_txbl_inc) < 500
gen denom_txbl_incm = soi_txbl_incm > 0

gen y_eitc = abs(soi_eitc - taxsim1_eitc) < 100
gen denom_eitc = soi_eitc > 0

gen y_ctc = abs(taxsim1_ctc + taxsim1_addl_ctc - soi_ctc_refundable  - soi_ctc_nonrefundable) < 100
gen denom_ctc = soi_ctc_refundable + soi_ctc_nonrefundable > 0

foreach k in `klist' {
	qui gen cond_`k' = y_`k' if denom_`k' > 0
}




*****************
*	Collapse	*
*****************

gcollapse (mean) y_* cond_* [iw=soi_wgt], fast


gen k = 1
reshape long y_ cond_, i(k) j(line) string
drop k

qui replace y_ = 1-y_
qui replace cond = 1 - cond_


tempfile touse

tostring y_ cond_, force format(%6.3f) replace
qui save `touse', replace




*********************************************
*											*
*				Write the table				*
*											*
*********************************************

local agistr "AGI"
local cgstr "Capital gains"
local ctcstr "Child tax credit"
local divstr "Qualified dividends"
local eitcstr "EITC"
local intstr "Taxable interest"
local pens_irastr "Taxable IRA and pensions"
local sched1str "Income from Sch. 1"
local txbl_incmstr "Taxable income"
local wagesstr "Wages"




cap file close myfile
file open myfile using "$outdir/tables/line_by_line.tex", write replace

*************
*	Header	*
*************
file write myfile " Line & Unconditional mismatch rate & Conditional mismatch rate \\ \hline "
file write myfile " & (1) & (2) \\ \hline "

	
foreach k in `klist' {
	use `touse', clear
	qui keep if line == "`k'"
	
	local line = line

	local cond = cond_[1]

	
	file write myfile " ``line'str' & `=y_[1]' & `cond'  \\ "
}




cap file close myfile



cap log close









